package aochulai.qisiren;

import baseFx.common.caching.AppCache;
import baseFx.common.caching.Cache;
import baseFx.common.utils.StringUtils;
import baseFx.common.utils.UrlUtils;
import baseFx.serialization.json.JsonUtils;
import baseFx.springboot.FxController;
import baseFx.springboot.anno.PathRestController;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@PathRestController("wx")
public class WxApi extends FxController {
    private static Cache cache = new AppCache();
    private static Logger logger = LoggerFactory.getLogger(WxApi.class);
    private static WxMpService wxService;

    static {
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        config.setAppId("wxb3b1e6e6613d2702");
        config.setSecret("f8b0cf31f1c0d06185b37b7485c36152");
        config.setToken("wxmsg");

        wxService = new WxMpServiceImpl();
        wxService.setWxMpConfigStorage(config);
    }

    @RequestMapping("")
    public void service(HttpServletResponse response) throws IOException {
        String signature = getStringParam("signature").orElse("");
        String nonce = getStringParam("nonce").orElse("");
        String timestamp = getStringParam("timestamp").orElse("");

        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            logger.warn("非法请求");
            return;
        }

        String echostr = getStringParam("echostr").orElse("");
        if (StringUtils.hasValue(echostr)) {
            response.getWriter().println(echostr);
            logger.info("验证通过");
            return;
        }
    }

    @RequestMapping("setMenu")
    public void setMenu() throws WxErrorException {
        WxMenu wxMenu = new WxMenu();
        WxMenuButton button = new WxMenuButton();
        button.setType("view");
        button.setUrl(App.domain + "/game.html");
        button.setName("进入游戏");
        wxMenu.setButtons(Arrays.asList(button));
        wxService.getMenuService().menuCreate(wxMenu);
    }

    @RequestMapping("getauthurl")
    public String getAuthUrl() {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        url = url.replace("{0}", wxService.getWxMpConfigStorage().getAppId());
        url = url.replace("{1}", App.domain + "/wx/getopenid");
        return url;
    }

    @RequestMapping("getopenid")
    public void getOpenId(HttpServletResponse response) throws WxErrorException, IOException {
        String code = getStringParam("code").get();
        WxOAuth2AccessToken token = wxService.getOAuth2Service().getAccessToken(code);
        response.sendRedirect(App.domain + "/game.html?pid=" + token.getOpenId() + "&host=" + UrlUtils.encode(App.domain));
    }

    @RequestMapping("jsconfig")
    public String getJsConfig() throws WxErrorException {
        String url = UrlUtils.decode(getStringParam("url").get());
        WxJsapiSignature sign = wxService.createJsapiSignature(url);
        return JsonUtils.toJson(sign);
    }
}
